package com.zw.yzk.kabu.adapter.header;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;


public final class WrapperAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    public static final int ITEM_VIEW_TYPE_HEADER = Integer.MAX_VALUE - 51;
    private final RecyclerView.Adapter originAdapter;
    private View header;


    public WrapperAdapter(RecyclerView.Adapter adapter) {
        this.originAdapter = adapter;
        header = null;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ITEM_VIEW_TYPE_HEADER) {
            return new RecyclerView.ViewHolder(header) {
            };
        }
        return originAdapter.onCreateViewHolder(parent, viewType);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (isHeaderRow(position)) {
            return;
        }
        int realPosition = position - getHeaderCount();
        originAdapter.onBindViewHolder(holder, realPosition);
    }

    @Override
    public int getItemCount() {
        return hasHeader() ? 1 + originAdapter.getItemCount() : originAdapter.getItemCount();
    }

    @Override
    public int getItemViewType(int position) {
        if (isHeaderRow(position)) {
            return ITEM_VIEW_TYPE_HEADER;
        } else {
            return originAdapter.getItemViewType(position - 1);
        }
    }

    @Override
    public long getItemId(int position) {
        if (isHeaderRow(position)) {
            return RecyclerView.NO_ID;
        } else {
            return originAdapter.getItemId(position);
        }
    }

    @Override
    public void setHasStableIds(boolean hasStableIds) {
        super.setHasStableIds(hasStableIds);
        originAdapter.setHasStableIds(hasStableIds);
    }

    public RecyclerView.Adapter getOriginAdapter() {
        return originAdapter;
    }


    public void setHeader(View header) {
        this.header = header;
        notifyDataSetChanged();
    }

    public void removeHeader() {
        this.header = null;
        notifyDataSetChanged();
    }

    public boolean isHeaderRow(int position) {
        return header != null && position == 0;
    }

    public boolean hasHeader() {
        return header != null;
    }

    public int getHeaderCount() {
        return header != null ? 1 : 0;
    }

}